//
//  GoodLsitViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/26.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "GoodLsitViewController.h"
#import "GoodListModel.h"
#import "GoodListTableViewCell.h"
#import "GetRegisterInforModel.h"
#import "ShopRegisterViewController.h"
#import "BatchimportViewController.h"
#import "LookInforViewController.h"
//批量改价控制器
#import "BatchconversionViewController.h"
@interface GoodLsitViewController ()<UIActionSheetDelegate>

@property(nonatomic,copy)NSString*SearchKeyWord;

@end

@implementation GoodLsitViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"GoodListTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.homeTableView.mj_header beginRefreshing];
    
    //导入成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Assignmentnote) name:@"SaveSuccessnote" object:nil];
}

- (void)Assignmentnote
{
    [self.homeTableView.mj_header beginRefreshing];
}

#pragma mark-tablevie代理方法


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodListData *data=self.dataArr[indexPath.row];
    
    GoodListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.isClick=self.isEdit;
    
    cell.deleStatue=self.deleStatue;//是否编辑状态
    
    cell.listModel=data;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodListData *data=self.dataArr[indexPath.row];
    if (self.isEdit) {
    
        if (self.deleStatue) {
            
            data.Seleclt=!data.Seleclt;
            
            [self ChangeStatues];
            
            [self.homeTableView reloadData];
            
            
        }else{
            //可以点击
            GetRegisterInforModel *model=[GetRegisterInforModel new];
            
            model.token=[LoginStatuesModel getUserToken];
            
            model.goodsId=[NSString stringWithFormat:@"%ld",data.goodsId];
            
            model.shopId=[NSString stringWithFormat:@"%ld",data.shopId];
            
            ShopRegisterViewController *EditGoods=[ShopRegisterViewController new];
            
            EditGoods.requrl=@"/index.php/FoodCheckApi/productAddInfo.json";
            
            EditGoods.Reqmodel=model;
            
            EditGoods.postUrl=@"/index.php/FoodCheckApi/productAdd.json";
            
            EditGoods.title=@"编辑商品";
            
            EditGoods.BtnStr=@"保存";
            
            EditGoods.OptionSussStr=@"保存成功";
            
            EditGoods.block=^()
            {
                
                [self.homeTableView.mj_header beginRefreshing];
            };
            
            
            [self.navigationController pushViewController:EditGoods animated:YES];
        }
        
    }else{//商品详情
        
        LookInforViewController *Infor=[LookInforViewController new];
        
        Infor.reqUrl=@"/index.php/FoodCheckApi/productDetail.json";
        
        Infor.params=@{@"goodsId":[NSString stringWithFormat:@"%ld",data.goodsId]};
        
        Infor.title=@"商品详情";
        
        [self.navigationController pushViewController:Infor animated:YES];
    }
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isEdit) {
        
        return YES;
    }
    
    return NO;
    
}


-(NSString*)getShopID{
    NSString * shopID;
    if ([self getUserType]==1) {
        shopID =[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    }else{
        shopID  = [NSString stringWithFormat:@"%ld",self.shopId];
    }
    
    return  shopID;
    
    
}


-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return @"删除";
    
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        GoodListData *data=self.dataArr[indexPath.row];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%ld",data.goodsId]];
        
        [self DelPostion:arr];
        
    }
    
}


-(void)DelPostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productDel.json" andrequestTime:5 andParams:@{@"goodsIds":params} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
     BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:ProductsListType];
    
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:ProductsListType andIsLookSelf:isSelf];
    
    Choose.SearchPlace=self.searchName;
    
     Choose.KeyWord=self.SearchKeyWord;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.SearchKeyWord=keyword;
        
        self.Reqmodel.params=paras;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for (GoodListData *data in self.dataArr) {
            
            data.Seleclt=NO;
            
        }
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    
    for (GoodListData *data in self.dataArr) {
        
        data.Seleclt=YES;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    for (GoodListData *data in self.dataArr) {
        
        data.Seleclt=NO;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for (GoodListData *data in self.dataArr) {
        
        if (data.Seleclt) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.goodsId]];
            
        }
        
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPostion:arr];
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (GoodListData *data in self.dataArr) {
        
        if (data.Seleclt) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"新增商品",@"批量导入",@"批量改价", nil];
    [sheet showInView:self.view];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { //新增商品
        
        GetRegisterInforModel *model=[GetRegisterInforModel new];
        
        model.token=[LoginStatuesModel getUserToken];
        
        if ([self getUserType]==1) {
            model.shopId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
        }else{
            model.shopId = [NSString stringWithFormat:@"%ld",self.shopId];
        }
        
        ShopRegisterViewController *AddGoods=[ShopRegisterViewController new];
        
        AddGoods.requrl=@"/index.php/FoodCheckApi/productAddInfo.json";
        
        AddGoods.Reqmodel=model;
        
        AddGoods.postUrl=@"/index.php/FoodCheckApi/productAdd.json";
        
        AddGoods.title=@"新增商品";
        
        AddGoods.BtnStr=@"保存";
        
        AddGoods.OptionSussStr=@"新增成功";
        
        AddGoods.block=^()
        {
            [self.homeTableView.mj_header beginRefreshing];
        };
        
        [self.navigationController pushViewController:AddGoods animated:YES];
    } else if (buttonIndex == 1) {//批量导入
        
        JobListModel *list=[JobListModel new];
        list.pageSize = 100;
        BatchimportViewController *GoodLsit=[BatchimportViewController new];
        
        if ([self getUserType]==1) {
            
            GoodLsit.isEdit=NO;
            
            GoodLsit.isdeleMore=NO;
            
            list.shopId=[LoginStatuesModel shopId];
        }else{
            
            GoodLsit.isEdit=NO;
            GoodLsit.isdeleMore=NO;
            
            if (self.shopId!=0) {
                list.shopId=self.shopId;
                GoodLsit.isEdit=NO;
                GoodLsit.AddBtnTitle = @"新增商品";
            }
            
            if ([self getUserType]==3) {
                
                list.marketId=[LoginStatuesModel getStaffId];
            }
            
        }
        
        GoodLsit.Reqmodel=list;
        
        
        GoodLsit.shopId = list.shopId;
        GoodLsit.searchName=@"输入商品名称";
        GoodLsit.AddBtnTitle=@"新增商品";
        
        GoodLsit.title=@"商品列表";
        
        [self.navigationController pushViewController:GoodLsit animated:YES];
    }else if (buttonIndex){
       DLog("你点击了第三个按钮")
       
        BatchconversionViewController *vc = [BatchconversionViewController new];
        vc.searchName = @"搜索商品";
        vc.AddBtnTitle = @"保存";
        vc.isEdit = YES;
        vc.shopId = self.shopId;
        
        
        [self.navigationController pushViewController:vc animated:YES];
        
        
        
    }
}
#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        GoodListModel *InforModel=[GoodListModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"商品"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
